package com.smart.village.big.screen.utils;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class DrzkApiClient {
    // 签名密钥（请替换为实际密钥）
    private static final String SIGNATURE_KEY = "EEXXXXXXXXXXXXXXXXXXXXXXVV";
    // API基础URL
    private static final String BASE_URL = "https://api-dev.drzk.cn/v2/car/temporarycar/parkingfee/parkid/";

    public static void main(String[] args) {
        try {
            // 测试GET请求
            sendGet();
            // 测试POST请求
            sendPost();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送GET请求
     */
    public static void sendGet() throws Exception {
        long timestamp = System.currentTimeMillis() / 1000;
        String parkId = "100010_0004";

        // 构建基础URL
        String encodedParkId = URLEncoder.encode(parkId, StandardCharsets.UTF_8.name()).toUpperCase();
        String requestUrl = BASE_URL + encodedParkId;

        // 构建请求参数
        Map<String, String> params = new HashMap<>();
        params.put("carNo", "粤B12345");

        // 处理参数
        String processedUrl = buildRequestUrl(requestUrl, params);

        // 生成签名字符串
        String secretString = processedUrl + "@#" + timestamp + "@#" + SIGNATURE_KEY;
        String signature = md5Encrypt(secretString);

        // 构建最终请求URL
        String finalUrl = processedUrl + "&signature=" + signature + "&t=" + timestamp;
        System.out.println("GET请求URL: " + finalUrl);

        // 发送请求
        String result = sendGetRequest(finalUrl);
        System.out.println("GET响应结果: " + result);
    }

    /**
     * 发送POST请求
     */
    public static void sendPost() throws Exception {
        long timestamp = System.currentTimeMillis() / 1000;
        String parkId = "100010_0004";

        // 构建基础URL
        String encodedParkId = URLEncoder.encode(parkId, StandardCharsets.UTF_8.name()).toUpperCase();
        String requestUrl = BASE_URL + encodedParkId;

        // 构建请求参数
        Map<String, String> params = new HashMap<>();
        params.put("carNo", "粤B12345");

        // 处理参数
        String processedUrl = buildRequestUrl(requestUrl, params);

        // 生成签名字符串
        String secretString = processedUrl + "@#" + timestamp + "@#" + SIGNATURE_KEY;
        String signature = md5Encrypt(secretString);

        // 添加签名和时间戳参数
        params.put("signature", signature);
        params.put("t", String.valueOf(timestamp));

        System.out.println("POST请求URL: " + requestUrl);
        System.out.println("POST请求参数: " + params);

        // 发送请求
        String result = sendPostRequest(requestUrl, params);
        System.out.println("POST响应结果: " + result);
    }

    /**
     * 构建带参数的请求URL
     */
    private static String buildRequestUrl(String baseUrl, Map<String, String> params) throws UnsupportedEncodingException {
        if (params == null || params.isEmpty()) {
            return baseUrl;
        }

        // 对参数进行URL编码并排序
        List<String> paramList = new ArrayList<>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            String key = entry.getKey();
            String value = URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.name()).toUpperCase();
            paramList.add(key + "=" + value);
        }
        Collections.sort(paramList);

        // 拼接参数
        return baseUrl + "?" + String.join("&", paramList);
    }

    /**
     * 发送GET请求
     */
    private static String sendGetRequest(String url) throws Exception {
        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL requestUrl = new URL(url);
            connection = (HttpURLConnection) requestUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            // 获取响应
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                return response.toString();
            } else {
                return "请求失败，响应码: " + connection.getResponseCode();
            }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    /**
     * 发送POST请求
     */
    private static String sendPostRequest(String url, Map<String, String> params) throws Exception {
        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL requestUrl = new URL(url);
            connection = (HttpURLConnection) requestUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 写入参数
            try (DataOutputStream out = new DataOutputStream(connection.getOutputStream())) {
                List<String> paramList = new ArrayList<>();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    paramList.add(entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.name()));
                }
                out.writeBytes(String.join("&", paramList));
                out.flush();
            }

            // 获取响应
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                return response.toString();
            } else {
                return "请求失败，响应码: " + connection.getResponseCode();
            }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    /**
     * MD5加密（大写）
     */
    private static String md5Encrypt(String strText) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(strText.getBytes(StandardCharsets.UTF_8));

            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    sb.append('0');
                }
                sb.append(hex);
            }
            return sb.toString().toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }
}